package first.niuke.simple;

/**
 * @ClassName NC11
 * @description:
 * @author: 荣燊
 * @create: 2021-06-14 21:50
 **/
public class NC11 {
    // 将升序数组转化为平衡二叉搜索树BST
    public TreeNode sortedArrayToBST (int[] num) {
        // write code here
        if (num == null) {
            return null;
        }
        return dfs(num, 0, num.length-1);
    }

    // 前序遍历,输入[-1,0,1,2]，输出[1,0,2,-1]
    // 根据示例的输出，知道根节点的选取规则是(left+right+1)/2,而不是(right+left)/2
    private static TreeNode dfs(int[] num, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left+right+1) / 2;
        TreeNode lnode = dfs(num, left, mid-1);
        TreeNode rnode = dfs(num, mid+1, right);
        TreeNode node = new TreeNode(num[mid]);
        if (lnode != null) {
            node.left = lnode;
        }
        if (rnode != null) {
            node.right = rnode;
        }
        return node;
    }

    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int root) {
        }
    }
}
